package daoImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import dao.BackForumDao;
import pojo.College;
import pojo.Question;
import utils.DateUtils;
import utils.DruidUtils;

public class BackForumDaoImpl implements BackForumDao{

	@Override
	public ArrayList<Question> getQuestion() {
		Connection conn = DruidUtils.getConnection();
		String sql = "select * from question";
		ArrayList<Question> qList = new ArrayList<Question>();
		try {
			PreparedStatement pre = conn.prepareStatement(sql);
			ResultSet res = pre.executeQuery();
			while(res.next()) {
				Question q = new Question();
				q.setQid(res.getInt("qid"));
				q.setqTitle(res.getString("qTitle"));
				q.setqContent(res.getString("qContent"));
				q.setUserid(res.getInt("userid"));
				q.setqTime(res.getDate("qTime"));
				q.setqFocusNum(res.getInt("qFocusNum"));
				q.setqAnswerNum(res.getInt("qAnswerNum"));
				qList.add(q);
			}
			res.close();
			pre.close();
			conn.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return qList;
	}

	@Override
	public int addQuestion(String qTitle, String qContent, int userid) {
		Connection conn = DruidUtils.getConnection();
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//		 Date date = null;
//		 try {
//			date = sdf.parse(qTime);
//		} catch (ParseException e1) {
//			e1.printStackTrace();
//		}
		String sql = "insert into question values(0,?,?,?,?,0,0)";
		PreparedStatement pre = null;
		try {
			pre = conn.prepareStatement(sql);
			pre.setString(1, qTitle);
			pre.setString(2, qContent);
			pre.setInt(3, userid);
			pre.setString(4, DateUtils.formDate(new Date(), "yyyy-MM-dd hh:mm:ss"));
			return pre.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				pre.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

	@Override
	public int delQuestion(int qid) {
		Connection conn = DruidUtils.getConnection();
		String sql = "delete from question where qid = ?";
		PreparedStatement pre = null;
		try {
			pre = conn.prepareStatement(sql);
			pre.setInt(1, qid);
			return pre.executeUpdate();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			try {
				pre.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return 0;
	}

}
